package yto.freemarker.java8.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * fork/join  并行流
 * 与多线程不同的是：多线程会等待
 * 并行流，没有任务的时候，会随机获取不同的队列去执行任务
 *
 * @author dongxing
 * @create 2018-06-23 16:11
 **/
public class ForkJoinCalculate extends RecursiveTask<Long> {

    private Long start;
    private Long end;

    //临界值
    private static final long TH = 1000;

    public ForkJoinCalculate(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {

        Long length = end - start;
        if (length <= TH) {
            long sum = 0;
            for (long i = start; i < end; i++) {
                sum += i;
            }
            return sum;
        } else {

            Long middle = (start + end) / 2;

            ForkJoinCalculate left = new ForkJoinCalculate(start, middle);
            left.fork();  //拆分子任务，同时压入线程队列

            ForkJoinCalculate right = new ForkJoinCalculate(middle + 1, end);
            right.fork();  //拆分子任务，同时压入线程队列

            return left.join() + right.join();
        }

    }
}
